<script>
import * as echarts from "echarts";
import axios from "../../api/axios.config";
import { useUserStore } from "@/stores/user";
import { mapStores } from "pinia";
import util from "../../api/util";
export default {
  data() {
    return {
      // 数据相关
      goodsList: [],
      searchKey: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      seller: null,
      offset: 0,
      // 状态控制
      detailVisible: false,
      formVisible: false,
      selectedGoods: null,
      goodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_stock: 0,
        goods_detail: 9,
        goods_desc: "",
      },

      // 表单验证规则
      formRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { max: 50, message: "长度不能超过50个字符", trigger: "blur" },
        ],
        goods_price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapStores(useUserStore),
    filteredGoods() {
      return this.goodsList.filter((item) =>
        item.goods_name.toLowerCase().includes(this.searchKey.toLowerCase()),
      );
    },
    formTitle() {
      return this.selectedGoods ? "编辑商品" : "新增商品";
    },
  },
  mounted() {
    this.seller = this.userStore.userId;
    this.loadGoods();
    console.log("###########################");
    console.log(this.seller);
    console.log(this.goodsList);
    console.log("###########################");
  },
  methods: {
    addGoods() {
      this.$router.push("/goods/addGoods");
    },
    async loadGoods() {
      // 调用API获取商品数据
      axios
        .get(
          `/goods/findbyseller?seller=${this.seller}&limit=10&offset=${(this.currentPage - 1) * this.pageSize}`,
        )
        .then((res) => {
          console.log(res);
          let lists = res.data.data.data;
          this.goodsList = lists.map(item => ({
          ...item,
          created_at: util.getTime(item.created_at),
          goods_price: parseFloat(item.goods_price)
        }));
          this.total = res.data.data.total;
          this.initChart();
        });
    },
    handleSearch() {
      axios
        .get(
          `/goods/findbyname?goods_name=${this.searchKey}&limit=10&offset=${(this.currentPage - 1) * this.pageSize}`,
        )
        .then((res) => {
          console.log(res);
          this.goodsList = res.data.data.data;
          this.total = res.data.data.total;
          this.initChart();
        });
    },
    showAddDialog() {
      this.formVisible = true;
      this.goodsForm = {
        goods_name: "",
        goods_price: 0,
        goods_stock: 0,
        goods_detail: 9,
        goods_desc: "",
      };
    },
    showDetail(row) {
      console.log("######################");
      console.log(this.detailVisible);
      console.log("######################");
      this.selectedGoods = row;
      this.detailVisible = true;
    },
    async toggleStatus(row) {
      let state = row.goods_status ? 0 : 1;
      try {
        axios
          .put(`/goods/setstatus?goods_id=${row.goods_id}&status=${state}&seller=${this.seller}`)
          .then((res) => {
            console.log(res);
            this.$message.success("状态更新成功");
            this.loadGoods();
          });
      } catch (err) {
        this.$message.error("操作失败");
        console.log(err);
      }
    },
    confirmDelete(row) {
      this.$confirm("确定要删除该商品吗？", "提示", {
        type: "warning",
      }).then(async () => {
        try {
          axios.delete(`/goods/delete/${row.goods_id}`).then((res) => {
            console.log("%%%%%%%%%%%%%%%%%%%");
            console.log(res);
            console.log("%%%%%%%%%%%%%%%%%%%");
            this.$message.success("删除成功");
            this.loadGoods();
          });
        } catch (err) {
          this.$message.error("删除失败");
          console.log(err);
        }
      });
    },
    initChart() {
      const chartDom = this.$refs.chart;
      const myChart = echarts.init(chartDom);

      const option = {
        title: { text: "商品浏览统计" },
        tooltip: {},
        xAxis: {
          type: "category",
          data: this.goodsList.map((item) => item.goods_name),
        },
        yAxis: { type: "value" },
        series: [
          {
            name: "浏览次数",
            type: "bar",
            data: this.goodsList.map((item) => item.browse_count),
          },
        ],
      };

      myChart.setOption(option);
    },
  },
};
</script>

<template>
  <div class="goods-management">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-input
        v-model="searchKey"
        placeholder="搜索商品名称"
        style="width: 300px; margin-left: 0px"
        clearable
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" plain @click="addGoods" style="margin-right: 20px"
        >新增商品</el-button
      >
    </div>
    <!-- 商品数据表格 -->
    <el-table
      :data="filteredGoods"
      border
      style="width: 100%"
      :default-sort="{ prop: 'created_at', order: 'descending' }"
    >
      <el-table-column prop="goods_id" label="ID" width="80" sortable />
      <el-table-column prop="goods_name" label="商品名称" width="200" />
      <el-table-column label="价格" width="120" sortable :sort="sortPrice" prop="goods_price">
        <template #default="{ row }">¥{{ row.goods_price.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column prop="goods_stock" label="库存" width="100" sortable />
      <el-table-column label="成色" width="100">
        <template #default="{ row }">{{ row.goods_detail }}成新</template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.goods_status ? 'success' : 'info'">
            {{ row.goods_status ? "上架中" : "已下架" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="browse_count" label="浏览次数" width="120" sortable />
      <el-table-column prop="created_at" label="创建时间" width="180" sortable />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="showDetail(row)">详情</el-button>
          <el-button
            size="small"
            :type="row.goods_status ? 'warning' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.goods_status ? "下架" : "上架" }}
          </el-button>
          <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="page-cut">
      <el-pagination
        background
        layout="prev, pager, next"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="loadGoods"
      />
    </div>
    <el-drawer
      v-model="detailVisible"
      title="商品详情"
      :size="isMobile ? '80%' : '500px'"
      :with-header="false"
      direction="rtl"
      class="custom-drawer"
    >
      <div v-if="selectedGoods" class="compact-detail">
        <el-descriptions
          :column="1"
          border
          label-class-name="compact-label"
          content-class-name="compact-content"
        >
          <el-descriptions-item label="商品ID">{{ selectedGoods.goods_id }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{
            selectedGoods.goods_name
          }}</el-descriptions-item>
          <el-descriptions-item label="价格">
            <span class="price-text">¥{{ selectedGoods.goods_price.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="库存">{{ selectedGoods.goods_stock }}</el-descriptions-item>
          <el-descriptions-item label="成色">
            <el-tag type="info">{{ selectedGoods.goods_detail }}成新</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="浏览次数">
            <el-icon><View /></el-icon>
            {{ selectedGoods.browse_count }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            selectedGoods.created_at
          }}</el-descriptions-item>
          <el-descriptions-item label="商品描述" class="full-width">
            <div class="description-text">{{ selectedGoods.goods_desc || "暂无描述" }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="formVisible" :title="formTitle">
      <el-form :model="goodsForm" label-width="100px" :rules="formRules">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="goodsForm.goods_name" />
        </el-form-item>
        <el-form-item label="价格" prop="goods_price">
          <el-input-number v-model="goodsForm.goods_price" :min="0" :precision="2" :step="10" />
        </el-form-item>
        <el-form-item label="库存" prop="goods_stock">
          <el-input-number v-model="goodsForm.goods_stock" :min="0" />
        </el-form-item>
        <el-form-item label="成色" prop="goods_detail">
          <el-select v-model="goodsForm.goods_detail">
            <el-option v-for="n in 9" :key="n" :label="`${10 - n}成新`" :value="10 - n" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="goodsForm.goods_desc" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 浏览数据图表 -->
    <div class="chart-container">
      <div ref="chart" style="height: 400px; margin-top: 30px"></div>
    </div>
  </div>
</template>

<style scoped>
.page-cut {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.goods-management {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  padding: 20px;
}

.chart-container {
  margin-top: 30px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}
header {
  height: 0px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .custom-drawer {
    --el-drawer-padding-primary: 15px;
    height: 0px;
  }
}

/* 标题样式 */
.drawer-title {
  margin: 0;
  color: var(--el-color-primary);
  font-size: 18px;
}

/* 紧凑布局 */
.compact-detail {
  padding: 15px;
}

/* 标签样式 */
:deep(.compact-label) {
  width: 100px !important;
  background-color: #f8f9fa;
  font-weight: normal;
  color: #606266;
}

/* 内容样式 */
:deep(.compact-content) {
  padding: 8px 12px !important;
  min-width: 200px;
}

/* 特殊字段样式 */
.price-text {
  color: var(--el-color-danger);
  font-weight: bold;
}

.description-text {
  line-height: 1.6;
  color: #909399;
}

.full-width {
  grid-column: 1 / -1;
}
</style>
